package org.example.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.Dto.StoryDTO;
import org.example.Entity.Story;
import org.example.Mapper.StoryMapper;
import org.example.Service.StoryService;
import org.example.Utils.OSSUtil;
import org.example.Vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class StoryServiceImpl extends ServiceImpl<StoryMapper, Story> implements StoryService {

    @Resource
    private OSSUtil ossUtil;

    @Autowired
    private StoryMapper storyMapper;

    @Override
    public R insertStory(StoryDTO story) throws IOException {
        MultipartFile imageFile = story.getImageFile();
        if (imageFile == null) {
            return R.error("请上传解释文件");
        }
        String imgUrl = ossUtil.upload(imageFile);
        Story insertStory = Story.builder()
                .titleEnglish(story.getTitleEnglish())
                .titleChinese(story.getTitleChinese())
                .interpretationEnglish(story.getInterpretationEnglish())
                .interpretationChinese(story.getInterpretationChinese())
                .image(imgUrl)
                .build();
        storyMapper.insert(insertStory);
        return R.ok();
    }

    @Override
    public R getStory(Integer id) {
        if (id == -1) {
            LambdaQueryWrapper<Story> wrapper = new LambdaQueryWrapper<>();
            List<Story> storyList = storyMapper.selectList(wrapper);
            return R.ok(storyList);
        }
        LambdaQueryWrapper<Story> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Story::getId, id);
        Story story = storyMapper.selectOne(wrapper);
        return R.ok(story);
    }
}
